import React, { useEffect, useState } from 'react'
import {Table,Button,Modal, Form, Input,} from 'antd'
import {DeleteOutlined,ExclamationCircleOutlined} from '@ant-design/icons'
import axios from 'axios'
const { confirm } = Modal;


export default function NewCategory(props) {
  const {username}=JSON.parse(localStorage.getItem('token'))
  const[dataSource,setDataSource]=React.useState([])
  const EditableContext = React.createContext(null);
  useEffect(()=>{
    axios.get(`http://localhost:8000/categories`).then(res=>{
      // ?author=${username}&auditState=0&_expand=category
        const list=res.data
        // console.log('list:',list);
         setDataSource(list)
    })
  },[username])

  const handleSave=(record,item)=>{
 setDataSource(dataSource.map(item=>{
  if(record.id===item.id){
    return {
      id:item.id,
      title:record.title,
      value:record.title
    }
  }
  return item
 }))
 axios.patch(`http://localhost:8000/categories/${record.id}`,{
  title:record.title,
  value:record.title
 })
// console.log(record);
  }
  const columns = [
    {
      title: 'ID',
      dataIndex: 'id',
      render:(id)=> {
        return <b>{id}</b>
      },
    },
    {
      title: '栏目名称',
      dataIndex: 'title',
      onCell: (record: DataType) => ({
        record,
        editable: true,
        dataIndex:"title",
        title:'栏目名称',
        handleSave:handleSave,
      }),
    },
    {
      title: '操作',
      render:(item)=>{
        return <div>
            <Button danger shape="circle"   onClick={()=>showDeleteConfirm(item) }  icon={<DeleteOutlined />}/>
        </div>  
      }
    },
  ];
  const showDeleteConfirm = (item) => {
    confirm({
      title: '你确认要删除吗?',
      icon: <ExclamationCircleOutlined />,
      // content: 'Some descriptions',
      okType: 'danger',
      okText: '确认',
      cancelText: '取消',
      onOk() {
       deleteMethod(item)
      },
      onCancel() {
        console.log('Cancel');
      },
    });
  };
  const deleteMethod=(item)=>{
    setDataSource(dataSource.filter(data=>data.id!==item.id))   
    // console.log('item',item)
    axios.delete(`http://localhost:8000/categories/${item.id}`)
  }
  const EditableRow = ({ index, ...props }) => {
    const [form] = Form.useForm();
    return (
      <Form form={form} component={false}>
        <EditableContext.Provider value={form}>
          <tr {...props} />
        </EditableContext.Provider>
      </Form>
    );
  };
  const EditableCell = ({
    title,
    editable,
    children,
    dataIndex,
    record,
    handleSave,
    ...restProps
  }) => {
    const [editing, setEditing] = useState(false);
    const inputRef = React.useRef(null);
    const form =  React.useContext(EditableContext);
    useEffect(() => {
      if (editing) {
        inputRef.current.focus();
      }
    }, [editing]);
    const toggleEdit = () => {
      setEditing(!editing);
      form.setFieldsValue({
        [dataIndex]: record[dataIndex],
      });
    };
    const save = async () => {
      try {
        const values = await form.validateFields();
        toggleEdit();
        handleSave({
          ...record,
          ...values,
        });
      } catch (errInfo) {
        console.log('Save failed:', errInfo);
      }
    };
    let childNode = children;
    if (editable) {
      childNode = editing ? (
        <Form.Item
          style={{
            margin: 0,
          }}
          name={dataIndex}
          rules={[
            {
              required: true,
              message: `${title} is required.`,
            },
          ]}
        >
          <Input ref={inputRef} onPressEnter={save} onBlur={save} />
        </Form.Item>
      ) : (
        <div
          className="editable-cell-value-wrap"
          style={{
            paddingRight: 24,
          }}
          onClick={toggleEdit}
        >
          {children}
        </div>
      );
    }
    return <td {...restProps}>{childNode}</td>;
  };

  return (
   <>
    <Table dataSource={dataSource}   components={{   
      body: {
          row: EditableRow,
          cell: EditableCell,
        },}
     
    } columns={columns} pagination={{ pageSize:5}} rowKey={item=>item.id}/>
   </>
  )
}
